package com.gs.api.weixin.web;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaMessage;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import com.gs.api.config.weixin.WxMaConfiguration;
import com.gs.api.core.Result;
import com.gs.api.weixin.entity.WxSubscribe;
import com.gs.api.weixin.service.WxSubscribeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.apache.commons.httpclient.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;

import javax.swing.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author guoyunfei on 2021/7/17 16:34
 * @className WxMessageController
 * @description TODO
 * @Version 1.0
 */
@Api(tags = "微信订阅消息")
@RestController
@RequestMapping("{appid}/subscribe")
public class WxSubscribeController{

    @Autowired
    private WxSubscribeService wxSubscribeService;


    @ApiOperation(value = "保存用户订阅信息", notes="保存用户订阅信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "appid", value = "微信appid", required = true, dataType = "String"),
            @ApiImplicitParam(name = "openid", value = "用户微信openid", required = true, dataType = "String"),
    })
    @PostMapping("saveSubscribe")
    public Result save(@PathVariable String appid, @RequestBody  WxSubscribe subscribe){
        subscribe.setAppid(appid);
        subscribe.setSubTime(new Date());
        wxSubscribeService.save(subscribe);
        return Result.success();
    }


    /**
     * 微信小程序推送订阅消息
     */
    @ApiOperation(value = "推送订阅消息", notes="推送订阅消息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "appid", value = "微信appid", required = true, dataType = "String"),
            @ApiImplicitParam(name = "name", value = "作品名称：高清壁纸馆", required = true, dataType = "String"),
            @ApiImplicitParam(name = "clazz", value = "作品分类：壁纸上新", required = true, dataType = "String"),
            @ApiImplicitParam(name = "content", value = "内容简介：高清壁纸馆上新作品啦！快来围观", required = true, dataType = "String"),
    })
    @GetMapping(value = "/sendSubscribeMessage")
    public void sendSubscribeMessage(@PathVariable String appid,String name,String clazz,String content) throws Exception {

        List<WxSubscribe> list = wxSubscribeService.selectSubscribeUsers(appid);

        int size = list.size();
        for (int i = 0; i < size; i++) {

            //多线程推送消息
            int finalI = i;

            new Thread(new Runnable(){
                @SneakyThrows
                @Override
                public void run() {

                    System.out.println(Thread.currentThread().getName() + "----------begin异步：>" + list.get(finalI).getId());

                    WxMaSubscribeMessage subscribeMessage = new WxMaSubscribeMessage();
                    //subscribeMessage.setMiniprogramState("developer");
                    //跳转小程序页面路径
                    subscribeMessage.setPage("pages/index/index");
                    //模板消息id
                    subscribeMessage.setTemplateId("LGgcBnpiEVaVrTHoDbOB49uYacrMbkSVYXSaGOvn8T0");
                    //给谁推送 用户的openid （可以调用根据code换openid接口)
                    subscribeMessage.setToUser(list.get(finalI).getOpenid());
                    //==========================================创建一个参数集合========================================================
                    ArrayList<WxMaSubscribeMessage.MsgData> wxMaSubscribeData = new ArrayList<>();
                    //作品名称
                    WxMaSubscribeMessage.MsgData name3 = new WxMaSubscribeMessage.MsgData("thing1", name);
                    wxMaSubscribeData.add(name3);
                    //分类
                    WxMaSubscribeMessage.MsgData thing1 = new WxMaSubscribeMessage.MsgData("thing2", clazz);
                    wxMaSubscribeData.add(thing1);
                    //内容简介
                    WxMaSubscribeMessage.MsgData thing4 = new WxMaSubscribeMessage.MsgData("thing4",content);
                    wxMaSubscribeData.add(thing4);
                    //发布时间
                    WxMaSubscribeMessage.MsgData time3 = new WxMaSubscribeMessage.MsgData("time3", DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
                    wxMaSubscribeData.add(time3);

                    //把集合给大的data
                    subscribeMessage.setData(wxMaSubscribeData);
                    //=========================================封装参数集合完毕========================================================
                    try {
                        //获取微信小程序配置：
                        final WxMaService wxService = WxMaConfiguration.getMaService(appid);
                        //进行推送
                        wxService.getMsgService().sendSubscribeMsg(subscribeMessage);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    System.out.println(Thread.currentThread().getName() + "----------end异步：>" + list.get(finalI).getId());
                    list.get(finalI).setDel_flag(0);

                    wxSubscribeService.removeById(list.get(finalI).getId());
                    Thread.sleep(500);
                }
                //do something

            }).start();


        }

    }





}
